package com.fulong.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.fulong.common.utils.JobList;
import com.fulong.service.Job.DeviceSqlJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fulong.entity.DeviceJobInfoEntity;
import com.fulong.service.DeviceJobInfoService;
import com.fulong.common.utils.PageUtils;
import com.fulong.common.utils.R;



/**
 * 
 *
 * @author fulong
 * @email ${email}
 * @date 2022-04-04 09:34:50
 */
@RestController
@RequestMapping("/devicejobinfo")
public class DeviceJobInfoController {
    @Autowired
    private DeviceJobInfoService deviceJobInfoService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = deviceJobInfoService.queryPage(params);
        Map<String, DeviceJobInfoEntity> jobmap = JobList.getJobmap();
        List<DeviceJobInfoEntity> list = (List<DeviceJobInfoEntity>)page.getList();
        List<DeviceJobInfoEntity> collect = list.stream().map(entiy -> {
            if (jobmap.get(entiy.getId()) != null) {
                entiy.setState(1);
            } else {
                entiy.setState(0);
            }
            return entiy;
        }).collect(Collectors.toList());
        page.setList(collect);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
		DeviceJobInfoEntity deviceJobInfo = deviceJobInfoService.getById(id);

        return R.ok().put("deviceJobInfo", deviceJobInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody DeviceJobInfoEntity deviceJobInfo) throws SchedulerException {
		deviceJobInfoService.save(deviceJobInfo);
        if(deviceJobInfo.getState()==1){
            Scheduler scheduler = JobList.getScheduler();
            Map<String, DeviceJobInfoEntity> jobmap = JobList.getJobmap();
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("tasksql" ,deviceJobInfo.getTasksql());
            jobDataMap.put("jdbcTemplate" , jdbcTemplate);
            JobDetail job = JobBuilder.newJob(DeviceSqlJob.class)
                    .withIdentity(deviceJobInfo.getId())
                    .setJobData(jobDataMap)
                    .withDescription(deviceJobInfo.getJobname())
                    .build();
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withSchedule(CronScheduleBuilder.cronSchedule(deviceJobInfo.getTimes()))
                    .withIdentity(deviceJobInfo.getId())
                    .build();
            scheduler.scheduleJob(job , trigger);
            jobmap.put(deviceJobInfo.getId() , deviceJobInfo);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/updateState")
    public R update(@RequestBody DeviceJobInfoEntity deviceJobInfo) throws SchedulerException {
        Scheduler scheduler = JobList.getScheduler();
        Map<String, DeviceJobInfoEntity> jobmap = JobList.getJobmap();
		deviceJobInfoService.updateById(deviceJobInfo);
        Integer state = deviceJobInfo.getState();
        if(state==1) {
            if(jobmap.get(deviceJobInfo.getId())!=null) {
                scheduler.resumeJob(JobKey.jobKey(deviceJobInfo.getId()));
            } else {
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("tasksql" ,deviceJobInfo.getTasksql());
                jobDataMap.put("jdbcTemplate" , jdbcTemplate);
                JobDetail job = JobBuilder.newJob(DeviceSqlJob.class)
                        .withIdentity(deviceJobInfo.getId())
                        .setJobData(jobDataMap)
                        .withDescription(deviceJobInfo.getJobname())
                        .build();
                CronTrigger trigger = TriggerBuilder.newTrigger()
                        .withSchedule(CronScheduleBuilder.cronSchedule(deviceJobInfo.getTimes()))
                        .withIdentity(deviceJobInfo.getId())
                        .build();
                scheduler.scheduleJob(job , trigger);
                jobmap.put(deviceJobInfo.getId() , deviceJobInfo);
            }
        } else {
                scheduler.deleteJob(JobKey.jobKey(deviceJobInfo.getId()));
                jobmap.remove(deviceJobInfo.getId());
        }
        return R.ok();
    }
    /*
    * 修改动态任务的源信息
    * */
    @RequestMapping("/updateJob")
    public R updateMateInfo(@RequestBody DeviceJobInfoEntity deviceJobInfo) throws SchedulerException {
        Scheduler scheduler = JobList.getScheduler();
        Map<String, DeviceJobInfoEntity> jobmap = JobList.getJobmap();
        if(jobmap.get(deviceJobInfo.getId())!=null){
            scheduler.deleteJob(JobKey.jobKey(deviceJobInfo.getId()));
            jobmap.remove(deviceJobInfo.getId());
        }
        scheduler.deleteJob(JobKey.jobKey(deviceJobInfo.getId()));
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("tasksql" ,deviceJobInfo.getTasksql());
        jobDataMap.put("jdbcTemplate" , jdbcTemplate);
        JobDetail job = JobBuilder.newJob(DeviceSqlJob.class)
                .withIdentity(deviceJobInfo.getId())
                .setJobData(jobDataMap)
                .withDescription(deviceJobInfo.getJobname())
                .build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withSchedule(CronScheduleBuilder.cronSchedule(deviceJobInfo.getTimes()))
                .withIdentity(deviceJobInfo.getId())
                .build();
        scheduler.scheduleJob(job , trigger);
        jobmap.put(deviceJobInfo.getId() , deviceJobInfo);
        deviceJobInfoService.updateById(deviceJobInfo);
        return R.ok();
    }
    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody String[] ids){
		deviceJobInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping("/test")
    public R test() throws SchedulerException {
        Scheduler scheduler = JobList.getScheduler();
        List<String> calendarNames = scheduler.getCalendarNames();
        for(String s : calendarNames) {
            System.out.println(s);
        }
        return R.ok();
    }
}
